package me.zhengjie.modules.gis.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.gis.domain.vo.MsgInfo;
import me.zhengjie.modules.gis.service.dto.AccessRecordQueryCriteria;
import me.zhengjie.modules.gis.service.impl.RoleService;
import me.zhengjie.utils.QRCodeUtil;
import me.zhengjie.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.sql.Date;
import java.util.UUID;

@Controller
@RequiredArgsConstructor
@Api(tags = "网页小工具接口")
@RequestMapping("/api/util")
public class UtilController {
    private static final Logger logger = LoggerFactory.getLogger(UtilController.class);
    private final RoleService roleService;
    @ApiOperation(value = "根据字符串生成二维码", produces = "application/octet-stream")
    @RequestMapping(value = "/getQrImage",method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadImage(@RequestParam(value = "message", required = false) String message,
                              @RequestParam(value = "useBack", required = false) Boolean useBack,
                              @RequestParam(value = "useLogo", required = false) Boolean useLogo,
                              @RequestParam(value = "transparent", required = false) Boolean transparent,
                              @RequestBody MsgInfo msg, HttpServletResponse response) {
        if (StringUtils.isBlank(message) && (msg == null || StringUtils.isBlank(msg.getMessage()))) {
            return ;
        }
        if (message == null) {
            message = msg.getMessage();
            useLogo = msg.getUseLogo();
            useBack = msg.getUseBack();
            transparent = msg.getTransparent();
        }
        if (useBack == null) {
            useBack = false;
        }
        if (useLogo == null) {
            useLogo = true;
        }
        if (transparent == null) {
            transparent = false;
        }
        //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
           /* String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");*/
        /*File file = new File(realPath, fileName);*/
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition",
                "attachment;fileName=qrCode.png");// 设置文件名
        try {
            BufferedImage bufferedImage = QRCodeUtil.createQRCode(message, useBack, useLogo, transparent);
            OutputStream os = response.getOutputStream();
            ImageIO.write(bufferedImage, "png", os);
            logger.info("生成二维码成功，生成信息：" + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "生成带有有效期的二维码", produces = "application/octet-stream")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url",value ="链接",paramType = "query", dataType="string", required = true),
            @ApiImplicitParam(name = "day",value ="有效期天数，不传则为0，表示当天有效",paramType = "query", dataType="Integer", defaultValue= "0")
    })
    @RequestMapping(value = "/getQrImageWithValidity",method = {RequestMethod.GET, RequestMethod.POST})
    public void getQrImageWithValidity(@RequestParam(value = "url") String url,
                              @RequestParam(value = "day", required = false) Integer day,
                           HttpServletResponse response) {
        if (StringUtils.isBlank(url)) {
            return ;
        }
        String vKey = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String newUrl = url + (url.contains("?") ? "&" : "?") + "vKey=" + vKey;
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("newurl", newUrl);
        response.addHeader("Content-Disposition",
                "attachment;fileName=qrCode.png");// 设置文件名
        try {
            BufferedImage bufferedImage = roleService.retrieveQrImage(url, vKey, day);
            OutputStream os = response.getOutputStream();
            ImageIO.write(bufferedImage, "png", os);
            logger.info("生成有效期二维码成功，生成信息：" + newUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成有效期二维码失败，生成信息：" + newUrl + "，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "验证链接有效性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url",value ="链接",paramType = "query", dataType="string", required = true),
            @ApiImplicitParam(name = "ip",value ="验证访问的ip地址，可不传",paramType = "query", dataType="string")
    })
    @RequestMapping(value = "/checkUrlValidity",method = {RequestMethod.GET})
    public ResponseEntity<Object> checkUrlValidity(@RequestParam(value = "url") String url,
                                                   @RequestParam(value = "ip", required = false) String ip) {
        return new ResponseEntity<>(roleService.validateUrl(url, ip), HttpStatus.OK);
    }

    @GetMapping(value = "queryUrlAccessRecord")
    @Log("查询URL有效期验证记录")
    @ApiOperation("查询URL有效期验证记录")
    public ResponseEntity<Object> queryUrlAccessRecord(AccessRecordQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(roleService.queryAccessRecords(criteria, pageable),HttpStatus.OK);
    }

    @GetMapping(value = "queryUrlValidate")
    @Log("查询URL有效期注册记录")
    @ApiOperation("查询URL有效期注册记录")
    public ResponseEntity<Object> queryUrlValidate(AccessRecordQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(roleService.queryUrlValidate(criteria, pageable),HttpStatus.OK);
    }

    @ApiOperation(value = "修改链接有效期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value ="url注册id",paramType = "query", dataType="int", required = true),
            @ApiImplicitParam(name = "valid",value ="有效期截止日",paramType = "query", dataType="string", required = true)
    })
    @RequestMapping(value = "/updateUrlValidDate", method = {RequestMethod.GET})
    public ResponseEntity<Object> updateUrlValidDate(@RequestParam(value = "id") Integer id,
                                                   @RequestParam(value = "valid") String valid) {
        roleService.updateUrlValidDate(id, valid);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "删除链接有效期")
    @ApiImplicitParam(name = "id",value ="url注册id",paramType = "query", dataType="int", required = true)
    @RequestMapping(value = "/deleteUrlValidate", method = {RequestMethod.GET})
    public ResponseEntity<Object> deleteUrlValidate(@RequestParam(value = "id") Integer id) {
        roleService.deleteUrlValidate(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
